package ThreadRunableVolite;

/**
 * @author Ajie
 * @date 2020-12-08
 * @function threada b交叉运行
 * Java 多线程交替打印1~100
 *  Object lock = new Object();
 *  lock.notify();
 *  lock.wait();
 *  2个线程，交替 notify ,wait.
 */
public class ThreadOrderAB_WaitNotify {

    static boolean DEBUG =false;
    volatile static int i=1;
    static int MAXCOUNT = 100;
    public static void main(String[] args) {
        Object lock = new Object();
        Thread aThread = new Thread(new Runnable() {

            @Override
            public void run() {

                System.out.println("A run。。。");
                while (true){
                    synchronized (lock) {
                        // 唤醒另一个线程
                        lock.notify();
                        if (i>MAXCOUNT){
                            return;
                        }
                        System.out.println("A拿到锁 work:" +(i++));

                        try {
                            if (DEBUG){
                                Thread.sleep(1000 * 1);
                                System.out.println("A 准备进入等待状态，调用 lock.wait()");
                            }
                            lock.wait();
                            if (DEBUG)
                            System.out.println("INFO: 有人唤醒了 A, A 重新获得锁 lock");
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    }
                }

            }
        });

        Thread bThread = new Thread(new Runnable() {

            @Override
            public void run() {

                System.out.println("B run。。。");
                while (true){
                    synchronized (lock) {
                        // 唤醒另一个线程
                        lock.notify();
                        if (i>MAXCOUNT){
                            return;
                        }
                        System.out.println("B拿到锁 work: "+(i++));
                        try {
                            if (DEBUG)
                            Thread.sleep(1000 * 1);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
        });

        aThread.start();
        bThread.setPriority(1);
//        try {
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        bThread.start();
    }



}
